<template>
  <div class="touxiang">
    <nav-bar
      class="user-changeInfo"
      title="修改头像"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
    >
      <template #right>
        <icon name="ellipsis" size="18" />
      </template>
    </nav-bar>
    <div class="fot">
      <Uploader
      :after-read="afterRead"
      v-model="fileList"
      multiple
      :max-count="1"
      style="margin: 10rem auto"
    />
    </div>

  </div>
  <Button type="primary" size="large" @click="touxiangHandel">确认修改</Button>
</template>
<script setup>
import { useRouter } from "vue-router";
import { NavBar, Toast, Icon, Button, Uploader } from "vant";
import { ref } from "vue";
import { changeInfoAPI, uploadFileAPI } from "../../services/auth";
import { urlImg } from "../../uitils/urlImg";
const { push } = useRouter();
const fileList = ref([]);
const uploaderImg = ref("");
const onClickLeft = () =>
  push({
    name: "changeInfo",
  });
const onClickRight = () => Toast("搜索");
// 保存修改头像
const afterRead = (file) => {
  // 此时可以自行将文件上传至服务器
  // console.log(file);
  const formData = new FormData();
  formData.append("file", file.file);
  uploadFileAPI(formData).then((res) => {
    uploaderImg.value = urlImg(res.data);
  });
};
const touxiangHandel = () => {
  // 头像更换
  changeInfoAPI({ avatar: uploaderImg.value }).then(() => {
    if (uploaderImg.value) {
      Toast.success("修改成功");
      setTimeout(() => {
        push({
          name: "changeInfo",
        });
      }, 2000);
    } else {
      Toast.fail("请上传头像");
    }
  });
};
</script>
<style scoped lang="scss">
.touxiang{
  .fot{
    text-align: center;
  }
}
</style>
